# -* - coding: UTF-8 -* -
#import sys
#reload(sys)
#sys.setdefaultencoding('utf8')

import threading,string,os
from base_thread import Thread
from time import sleep
from task import *
from notify.client import *
from notify.task import *
import logging


#从外部队列读取消息放入内部对列
class NotifyCenter():  
	def __init__(self,file_name):
		self.cache_file=file_name
		self.queue=Thread.Queue()
		self.clients = {}
		
			
	#读取暂存的命令
	def load(self):
		if os.path.isfile(self.cache_file):
			f=open(self.cache_file,'r')
			for line in f:
				if line.strip():
					req=NotifyClient('')
					req.fromJson(line.strip())
					self.clients[req.command][req.url]=req
			f.close()
	
	#保存已有的命令
	def save(self):
		f=open(self.cache_file,'w')
		for c in self.clients:
			for u in self.clients[c]:
				line = u.toJson()
				f.write(line+"\n")
		# 获取队列 
		f.close()			
	
	#注册成订阅者
	def register_client(self,command,url,data):
		logging.info(url)
		exists=True
		if not (command in self.clients):
			self.clients[command]={}
			exists=False
		elif not (url in self.clients[command]):
			exists=False
		if not exists:
			req=NotifyClient(command,url,data)
			self.clients[command][url]=req
	
	#移动订阅者	
	def remove_client(self,command,url):
		logging.info(url)
		if command in self.clients:
			if url in self.clients[command]:
				del self.clients[command][url]
		
	#执行命令
	def execute(self,task):
		if task.command in self.clients:
			for k,v in self.clients[task.command].items():
				self.queue.put(NotifyTask(task.command,v,task.data))
